const _api = require('../../utils/api.js');
const apiurl = require('../../utils/apiurl/public.js');
const urls = [
  {id:1,url:'http://img.qiuqiumedia.com/uploads/video/20230517/820w712175339.m3u8',objectFit:'cover',allowPlay:true},
  {id:2,url:'http://img.qiuqiumedia.com/uploads/video/20230517/ggya8z2180700.m3u8',objectFit:'cover',allowPlay:true},
  {id:3,url:'http://img.qiuqiumedia.com/uploads/video/20230517/y428gld180536.m3u8',objectFit:'cover',allowPlay:false},
  {id:4,url:'http://img.qiuqiumedia.com/uploads/video/20230517/0v23ffx180446.m3u8',objectFit:'cover',allowPlay:false},
  {id:5,url:'http://img.qiuqiumedia.com/uploads/video/20230517/l6zefzd180205.m3u8',objectFit:'cover',allowPlay:false},
  {id:6,url:'http://img.qiuqiumedia.com/uploads/video/20230517/51r8ok5175928.m3u8',objectFit:'cover',allowPlay:false},
]
  
const videoList = []
  Page({
    data: {
      currentTimestr:'',//当前时间
      durationstr:'',//总时长
      currentTime:null,//当前时间
      duration:null,//总时长
      sliderValue:0,//进度条的值
      updateState: false, //防止视频播放过程中导致的拖拽失效
      isPlaying:false,//是否正在播放
      videoList:[],
      playId:1,
      current_index: 0, // 这个参数可以控制从第几个视频开始播放（可以从onLoad动态修改这个参数）
      videoId:0,//视频id
      list:[],//集数列表
      showlist:[],//集数列表
      cflist:[],//拆分后的集数列表
      isControls:false,
      videoTitle:'',//视频标题
      recent:'',//最新集数
      isfav:0,//是否已加入追剧
      showPay:false,//是否显示底部充值
      allowplay:false,//是否允许播放
      showModal:false,
      botindex:0,//底部选集展示的index
      isshowdom:false,
      myindex:null,//自定义下标
      getuser:null,//从接口获取的用户信息
    },

    onPlay(e) {},
    onChange(e){
 
    // console.log(555);
    //   if(e.detail.activeId){
    //     // let zsallowplay=this.data.list[e.detail.activeId-1].allowPlay
    //     let zsallowplay=this.data.list[e.detail.activeId-1].allowPlay
    //     this.setData({
    //       playId:e.detail.activeId,
    //       allowplay:zsallowplay
    //     })
    //   }
  
    },
    onPause(e) {
      //  console.log('pause', e.detail.activeId)
    },
  
    onEnded(e) {
        const childComponent = this.selectComponent('#videocomponent');

            childComponent.autoNext();

    },
  
    onError(e) {},
  
    onWaiting(e) {},
    onUpdataVideo(e){

    },
    
    onTimeUpdate(e) {
        if (this.data.updateState) { //判断拖拽完成后才触发更新，避免拖拽失效
            // console.log(e.detail.myindex)
            // console.log(this.data.myindex)
            if(this.data.myindex==null){
                this.setData({
                    myindex:0
                })
            }
            if(e.detail.myindex==this.data.myindex){
                // console.log(e.detail);
                // console.log(888)
                let sliderValue = e.detail.currentTime / e.detail.duration * 100;
                this.setData({
                    sliderValue,
                    duration: e.detail.duration,
                    currentTimestr:this.getTime(e.detail.currentTime),
                    durationstr:this.getTime(e.detail.duration),
                })
            }
        }
      
    },
    
    onProgress(e) {},
  

  
    onLoadedMetaData(e) {
      // console.log('LoadedMetaData', e)
    },
    getplaying(e){
        this.setData({
            isPlaying:e.detail.val
        })
        if(e.detail.val){
            this.setData({
                updateState:true
            })
        }else{
            this.setData({
                updateState:false
            })
        }
    },
    getplayid(e){
        console.log(e.detail.myindex)
        this.setData({
            myindex:e.detail.myindex,
            current_index:e.detail.myindex,
            // currentTimestr:'',//当前时间
            // durationstr:'',//总时长
            // currentTime:null,//当前时间
            // duration:null,//总时长
            // sliderValue:0,//进度条的值
            // updateState: false, //防止视频播放过程中导致的拖拽失效
            isControls:false
        })
        let findarr=this.data.list[e.detail.myindex]
        if(findarr){
            if(!findarr.allowPlay){
                // this.openPay()
                this.getChapterdetail(e.detail.myindex)
            }
        }
    },
    getid(e){
        // console.log(e.detail.id);
        let find=this.data.list[e.detail.myindex]
        if(find){
            this.setData({
                allowplay:find.allowPlay
            })
        }
        this.setData({
            isControls:!this.data.isControls
        })
        // console.log(45);
    },
    openTopup(){//打开选集
      this.setData({showModal:true})
  },
  gotoPlay(e){
    // console.log(e.currentTarget.dataset.playnum);
    // console.log(e.currentTarget.dataset.id);
    // console.log(e.currentTarget.dataset.myindex);

    this.setData({
        playId:e.currentTarget.dataset.id,
        myindex:e.currentTarget.dataset.myindex
    })
    
    let findarr=this.data.list[e.currentTarget.dataset.myindex]
        if(findarr){
            if(!findarr.allowPlay){
                // this.openPay()
                this.setData({
                    isshowdom:false,
                })
                this.setData({
                    current_index:findarr.myindex,
                    showModal:false
                })
                this.setData({
                    isshowdom:true,
                })
                this.getChapterdetail(findarr.myindex)
            }else{
                this.setData({
                    isshowdom:false,
                })
                this.setData({
                    current_index:findarr.myindex,
                    showModal:false
                })
                this.setData({
                    isshowdom:true,
                })
            }
            _api.get(apiurl.chapterinfo,{video_id:this.data.videoId,chapnum:this.data.list[this.data.myindex].chapnum}).then(res=>{

            })
        }
    
  },
  gotoPlay2(ind){
    this.setData({
        isshowdom:false,
    })
    this.setData({
        current_index:ind,
        showModal:false
    })
    // let findarr=this.data.list[playnum-1]
    //     if(findarr){
    //         if(!findarr.allowPlay){
    //             this.getChapterdetail(playnum)
    //             // this.openPay()
    //         }
    //     }
    this.setData({
        isshowdom:true,
    })
    _api.get(apiurl.chapterinfo,{video_id:this.data.videoId,chapnum:this.data.list[this.data.myindex].chapnum}).then(res=>{

    })
  },
  sliderChange(e){//完成一次拖动后触发的事件，event.detail = {value}
    console.log(this.data.duration);
    console.log(6666)
        if (this.data.duration) {
            // var videoContextCurrent = wx.createVideoContext('myVideo' + this.data.currentIndex)
            // videoContextCurrent.seek(e.detail.value / 100 * this.data.duration); //完成拖动后，计算对应时间并跳转到指定位置
            // videoContextCurrent.play()
            const childComponent = this.selectComponent('#videocomponent');
            childComponent.gotoTime(e.detail.value,this.data.duration);
            this.setData({
                sliderValue: e.detail.value,
                isPlaying:true,
                updateState: true //完成拖动后允许更新滚动条
            })
        }
    },
  sliderChanging(e){//拖动过程中触发的事件，event.detail = {value}
    const childComponent = this.selectComponent('#videocomponent');
    childComponent.stopvideo();
    this.setData({
        updateState: false, //拖拽过程中，不允许更新进度条
        isPlaying:false,
    })
    },
  playorstop(){
    const childComponent = this.selectComponent('#videocomponent');
    childComponent.playvideo();
  },

  getTime(time) {//秒数转为分秒
    // 转换为式分秒
    let h = parseInt(time / 60 / 60 % 24)
    h = h < 10 ? '0' + h : h
    let m = parseInt(time / 60 % 60)
     m = m < 10 ? '0' + m : m
    let s = parseInt(time % 60)
     s = s < 10 ? '0' + s : s
    // 作为返回值返回
    return m+":"+s
},
  addAfter(){
    _api.post(apiurl.addfavorite,{video_id:this.data.videoId}).then(res=>{
        if(res.data.code==0){
            wx.showToast({
                title: '加入成功！',
            })
            setTimeout(()=>{
                wx.hideToast()
                this.setData({
                    isfav:1
                })
            },1000)
        }
    })
},
  hideModal(){//关闭选集
    this.setData({showModal:false})
},
  changeBot(e){//切换底部的剧集分组
        
      // console.log(e.currentTarget.dataset.index)
      this.setData({
          botindex:e.currentTarget.dataset.index
      })
  },
    getDetial(){//或取视频详情
      wx.showLoading({
        title: '数据加载中',
      })
      _api.get(apiurl.videoinfo,{id:this.data.videoId,page:1,limit:20}).then(res=>{
        wx.hideLoading()
        if(res.data.code==0){
          this.setData({
            videoTitle:res.data.data.title,
            recent:res.data.data.chapter_recent,
            isfav:res.data.data.is_fav
          })
        }
      })
    },
    getChapter(){//获取视频的集数列表
        wx.showLoading({
          title: '数据加载中',
        })
        this.setData({
            isshowdom:false,
        })
        _api.get(apiurl.chapterindex,{video_id:this.data.videoId,page:1,limit:200}).then(res=>{
          wx.hideLoading()
          if(res.data.code==0){
           
            let zslist=[]
            zslist=res.data.data.map((item,index)=>{
                item.url=item.video_url
                item.id=item.chapnum
                item.myindex=index
                item.idxKey=item.chapnum
                item.objectFit='cover'
                if(item.ispayd==1){
                    if(item.is_sale==1){
                        item.allowPlay=true
                    }else{
                        item.allowPlay=false
                    }
                }else{
                    item.allowPlay=true
                }
                return item
                // zslist.push(item)
            })
            console.log(zslist)
            // for(let item of res.data.data){
                
            // }
            let zfdata=this.splitArray(zslist,9)//拆分数组
            this.setData({
                list:zslist,
              cflist:zfdata,
              isshowdom:true
            })
            // console.log(this.data.list);
            if(this.data.haveparams){
            //   this.getChapterdetail(this.data.paramsnum)
            }else{
            //   this.getChapterdetail(0)
            }
          }
        })
      },
      splitArray(array, size){
        let data = [];
        for (let i = 0; i < array.length; i += size) {
        data.push(array.slice(i, i + size))
        }
        return data
    },
    changeControls(){//修改是否展示视频控制
      let nucontrol=!this.data.isControls
      this.setData({
        isControls:nucontrol
      })
    },
    openPay(){//打开充值框
        this.setData({showPay:true})
    },
    hidePay(){//关闭充值框
        this.setData({showPay:false})
    },
    getProduct(){//获取充值项目
        _api.get(apiurl.rechargeitem).then(res=>{
            if(res.data.code==0){
                this.setData({
                    product:res.data.data
                })
            }
        })
    },
    getCode(){
        wx.login({
            success:res=>{
              var code=res.code
              if(code){
                  wx.getUserInfo({
                    success:ures=>{
                      _api.post(apiurl.login,{js_code:code,encryptedData:ures.encryptedData,iv:ures.iv}).then(loginres=>{
                          console.log(232323);
                          console.log(loginres.data);
                          if(loginres.data.code==0){
                            wx.setStorageSync('token', loginres.data.data.token)
                            this.setData({
                                allowplay:true,
                                })
                            this.getUserinfo()
                          }else{
                            wx.showToast({
                                title: '登录失败！',
                                icon:"error"
                              })
                              setTimeout(()=>{
                                wx.hideToast()
                              },1500)
                          }
                        })
                    }
                  })
              }
            }
          })
       
        
      },
      getUserinfo(){//获取用户信息
        _api.get(apiurl.userinfo).then(res=>{
            if(res.data.code==0){
                this.setData({
                    getuser:res.data.data
                })
                wx.setStorageSync('getuser', res.data.data)
            }
        })
    },
    gotoBack(){//退出页面前提示
        const pages = getCurrentPages()
        if (pages.length > 1) {
            wx.navigateBack({
                delta: 1  // 返回的页面数，如果是1就是返回上一页
              })
        } else {
            wx.switchTab({
              url: '/pages/list/list',
            })
        }
       
        
    },
    checkPay(e){//选择充值的项
        let id=e.currentTarget.dataset.id
        let _this=this
        _api.post(apiurl.ordercreate,{id:id}).then(res=>{
            if(res.data.code==0){
                wx.requestPayment({
                    timeStamp: res.data.data.timeStamp,
                    nonceStr: res.data.data.nonceStr,
                    package: res.data.data.package,
                    signType: res.data.data.signType,
                    paySign: res.data.data.paySign,
                    success (res) { 
                        console.log(res);
                        console.log("成功");
                        _this.setData({
                            showPay:false
                        })
                        _this.hideModal()
                        _this.getProduct()
                        console.log(_this.data.myindex)
                        console.log(_this.data.current_index)
                        // _this.getChapterdetail(_this.data.myindex)
                        _this.getChapterdetail(_this.data.current_index)
                        _this.getUserinfo()
                    },
                    fail (res) { 
                        console.log(res);
                        console.log("失败");
                    }
                  })
            }
        })
    },
    getChapterdetail(ind){//获取某一集的信息
        console.log(ind);
        var _this=this
        wx.showLoading({
            title: '数据加载中',
        })
        let hde=ind

        let findobj=this.data.list[ind]
        if(findobj){
            _api.get(apiurl.chapterinfo,{video_id:this.data.videoId,chapnum:findobj.chapnum}).then(res=>{
                wx.hideLoading() 
                if(res.data.code==0){//如果正常播放
                    
                    this.setData({
                        allowplay:true,
                        isPlaying:true,
                        updateState: true
                    })
                    if(this.data.list[ind].allowPlay){
                        this.gotoPlay2(ind)
                    }else{
                        if(res.data.data.ispayd==1){
                            let xb=`list[${ind}].allowPlay`
                            this.setData({
                                [xb]:true
                            })
                            console.log(this.data.list)
                            this.gotoPlay2(ind)
                        }
                    }
                    
                    

                    if(this.data.list[hde].ispayd==1){
                        let ind2=hde%9
                        let xiabiao=`cflist[${this.data.botindex}][${ind2}].is_sale`
                        this.setData({
                            [xiabiao]:1
                        })
                        console.log(this.data.cflist)
                        console.log(55555555555)
                    }
    
    
                }else if(res.data.code==103){//如果没有登录
                    const childComponent = this.selectComponent('#videocomponent');
                    childComponent.stopvideo();
                    this.setData({
                        isControls:false,
                        allowplay:false,
                        isPlaying:false,
                    })
                    wx.showModal({
                        title: '提示',
                        content: '请先登录！',
                        success (res) {
                            if (res.confirm) {    
                                _this.getCode()
                            } else if (res.cancel) {
                                console.log('用户点击取消')
                            }
                        }
                    })
                }else if(res.data.code==105){//如果k币不足
                    console.log(45454)
                    const childComponent = this.selectComponent('#videocomponent');
                    childComponent.stopvideo();
                    this.setData({
                        isControls:false,
                        isPlaying:false,
                        allowplay:false,
                    })
                    
                    let _this=this
                    _this.openPay()
                    console.log(21212)
                
                    
                }
            })
        }
        
        
    },
    onLoad(options) {
        this.setData({
            videoId:options.id
        })
        if(options.num){
            console.log(options.num)
            this.setData({
                current_index:options.num-1,
                myindex:options.num-1
            })
        }
        if(options.channel_id){
            wx.setStorageSync('channelid',options.channel_id)
        }
        this.getDetial()
        this.getChapter()
        this.getProduct()
        this.getUserinfo()
    },
    setread(){
       
    },
    onHide() {
        console.log('监听页面隐藏')
        // _api.get(apiurl.chapterinfo,{video_id:this.data.videoId,chapnum:this.data.list[this.data.myindex].chapnum}).then(res=>{

        // })
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        console.log('监听页面卸载')
       
        

    },



  })
  